//
//  ZHUserDefaults.m
//  ToolsEnginer
//
//  Created by 正合适 on 2017/6/1.
//  Copyright © 2017年 正合适. All rights reserved.
//

#import "ZHUserDefaults.h"
#import "ZHCache.h"

@implementation ZHUserDefaults
#pragma mark - ---------- public method ---------
#pragma mark - 保存对象
+ (void)setObject:(id)object forKey:(NSString *)key {
    NSString *jsonString = @"";
    if ([object isKindOfClass:[NSObject class]]) {
        jsonString = [ZHUserDefaults jsonString:object];
    }
    [ZHCache cacheWithKey:key value:jsonString table:[ZHUserDefaults tableName]];
}

#pragma mark - 获取对象
+ (id)getObjectWithKey:(NSString *)key {
    NSString *jsonString = [ZHCache fromCacheWithKey:key table:[ZHUserDefaults tableName]];
    return [ZHUserDefaults objectFromjsonString:jsonString];
}

#pragma mark - 保存BOOL值
+ (void)setBool:(BOOL)boolVal forKey:(NSString *)key {
    NSString *val = boolVal?@"YES":@"NO";
    [ZHCache cacheWithKey:key value:val table:[ZHUserDefaults tableName]];
}

#pragma mark - 获取BOOL值
+ (BOOL)getBoolWithKey:(NSString *)key {
    NSString *result = [ZHCache fromCacheWithKey:key table:[ZHUserDefaults tableName]];
    return [result isEqualToString:@"YES"]?YES:NO;
}


#pragma mark - ---------- private method ----------
#pragma mark - object转为sring
+ (NSString *)jsonString:(id)obj {
    if (![NSJSONSerialization isValidJSONObject:obj]) {
        return @"";
    }
    return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
}

#pragma mark - jsonString转为object
+ (id)objectFromjsonString:(NSString *)jsonString{
    return [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
}

#pragma mark - 表名
+ (NSString *)tableName {
    return NSStringFromClass([ZHUserDefaults class]);
}


@end
